﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using Aandelendelen.Mail;
using Aandelendelen.Db;
using Aandelendelen.Obs;

namespace Aandelendelen
{
	public partial class ActivateAdAccount : BaseForm
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!this.IsPostBack)
			{
				this.Activate();
			}
		}

		private void Activate()
		{
			try
			{
				string uid = this.ActivateStep1();

				this.ActivateStep2(uid);

				this.Label1.Text = "Uw account is succesvol geactiveerd.";

				this.SendConfirmationMail(uid);

				this.Panel1.Visible = true;
			}
			catch (Exception e)
			{
				this.Panel1.Visible = false;

				this.Label1.Text = e.Message;
			}
		}

		private string ActivateStep1()
		{
			string uid = this.Request.QueryString["uid"];

			if (uid == null)
				throw new Exception("Deze pagina mag niet zomaar aangeroepen worden.");

			Query query = new Query("s_inactiveaduid", "uid", uid, OleDbType.Char);

			string foundUid = (string)query.Execute();
			if (foundUid == null)
				throw new Exception("Dit account bestaat niet of is reeds geactiveerd.");

			return foundUid;
		}

		private void ActivateStep2(string uid)
		{
			Query query = new Query("u_activateaduid", "uid", uid, OleDbType.Char);

			int rows = (int)query.Execute();

			if (rows == 0)
				throw new Exception("Dit account bestaat niet of is reeds geactiveerd.");
		}

		private void SendConfirmationMail(string uid)
		{
			Query query = new Query("s_adnawimpersonate", "Gebruikersnaam", uid, OleDbType.Char);

			ResultSet resultSet = (ResultSet)query.Execute();

			AdvertiserInfo userInfo = new AdvertiserInfo(resultSet);

			MailArguments mailArgs = MailArguments.MailArgs;
			mailArgs.Clear();

			mailArgs["{aanhef}"] = userInfo.MailAanhef;
			mailArgs["{username}"] = uid;

			EMail email = MailCache.GetMail("adaccountactivated");
			email.Recipients = userInfo.Email;

			email.QueueSingle();
		}
	}
}